<?php

	class moving {
		

		function moving() {
			global $admin;
		}
		
		function index() {
			global $db, $segment, $config, $smarty, $admin;

		    $temp = $_GET;
		    $cond = '';
		    unset($temp['m']);
		    unset($temp['s']);
		    if(!empty($temp)){
		        $cond = http_build_query($temp);
		    }
		    $smarty->assign("cond", $cond);
		}


		function create() {
			global $db, $smarty, $segment, $config, $admin;
			
			if(!empty($_POST["action"]) && $_POST["action"]=="create") {
				if(empty($_POST["shopid_from"])) $errors["empty_shopid_from"] = true;
				elseif(empty($_POST["shopid_to"])) $errors["empty_shopid_to"] = true;
				elseif($_POST["shopid_from"]==$_POST["shopid_to"]) $errors["same_shopid"] = true;
				if(empty($_POST["title"])) $errors["empty_title"] = true;
				
// 				$productid = $db->qstr($_POST["productid"]);
// 				if(empty($errors)) if(!$db->getone("select count(1) from {$config->db_prefix}products where id=$productid")) $errors["unexist_product"] = true;

				if(empty($errors)) {
					$shopid_from = $db->qstr($_POST["shopid_from"]);
					$shopid_to = $db->qstr($_POST["shopid_to"]);
					$shop_from = $db->qstr($db->getone("select title from {$config->db_prefix}shops where id=$shopid_from"));
					$shop_to = $db->qstr($db->getone("select title from {$config->db_prefix}shops where id=$shopid_to"));
					$title = $db->qstr($_POST["title"]);
					$admin_remark = $db->qstr($_POST["admin_remark"]);
					
					$sqlstr = "insert into {$config->db_prefix}moving_paper (`title`, shopid_from, shop_from, shopid_to, shop_to, admin_remark, create_user) values ($title, $shopid_from, $shop_from, $shopid_to, $shop_to, $admin_remark, '{$_SESSION['ADMIN_USER']}')";
					$result = $db->execute($sqlstr);
					if($result) header("location:{$config->site_admin}m=inventory&s=moving.php");
				}
				
				if(!empty($errors)) $smarty->assign("errors", $errors);								
			}			
		}
		
		function modify() {
			global $db, $smarty, $segment, $config, $admin;
			
			if(!empty($_POST["action"]) && $_POST["action"]=="modify") {


// 				$thedate = strtotime($_POST["Date_Year"]."-".$_POST["Date_Month"]."-".$_POST["Date_Day"]);
// 				$smarty->assign("thedate", $thedate);
				
// 				if(empty($_POST["shopid_from"])) $errors["empty_shopid_from"] = true;
// 				elseif(empty($_POST["shopid_to"])) $errors["empty_shopid_to"] = true;
// 				elseif($_POST["shopid_from"]==$_POST["shopid_to"]) $errors["same_shopid"] = true;
// 				if(empty($_POST["product"])) $errors["empty_product"] = true;
// 				if(empty($_POST["number"]) || $_POST["number"]==0) $errors["empty_number"] = true;
				
// 				$productid = $db->qstr($_POST["productid"]);
// 				if(empty($errors)) if(!$db->getone("select count(1) from {$config->db_prefix}products where id=$productid")) $errors["unexist_product"] = true;

// 				if(empty($errors)) {
// 					$id = $db->qstr($_POST["id"]);
// 					$shopid_from = $db->qstr($_POST["shopid_from"]);
// 					$shopid_to = $db->qstr($_POST["shopid_to"]);
// 					$shop_from = $db->qstr($db->getone("select title from {$config->db_prefix}shops where id=$shopid_from"));
// 					$shop_to = $db->qstr($db->getone("select title from {$config->db_prefix}shops where id=$shopid_to"));
// 					$product = $db->qstr($_POST["product"]);
// 					$spec = $db->qstr($_POST["spec"]);
// 					$unit = $db->qstr($_POST["unit"]);
// 					$number = $db->qstr($_POST["number"]);
// 					$memo = $db->qstr($_POST["memo"]);
					
// 					$sqlstr = "update {$config->db_prefix}moving set shopid_from=$shopid_from, shop_from=$shop_from, shopid_to=$shopid_to, shop_to=$shop_to, productid=$productid, product=$product, spec=$spec,
// 					 unit=$unit, number=$number, memo=$memo, thedate=$thedate where id=$id";
// 					print $sqlstr;
// 					$result = $db->execute($sqlstr);
// 					if($result) header("location:".(empty($_POST["referer"])?"{$config->site_index}admin/moving":$_POST["referer"]));
// 				}
				
// 				if(!empty($errors)) $smarty->assign("errors", $errors);								
			}			
		}
		

		function delete() {
			global $db, $segment, $config, $admin;

			
			

		}

		/**
		 * 获取调拨单的商品信息
		 */
		function getProductList(){
		    global $db, $segment, $config, $admin;
		    $id = $db->qstr($_GET['paper_id']);
		    $sql = "select a.*,b.pid,b.pic,c.barcode from {$config->db_prefix}moving as a left join haiou_product_sku as b on a.productid=b.id left join haiou_stock_products c on a.productid=c.product_sku_id where a.paper_id={$id} order by a.id asc";
		    $res = $db->GetArray($sql);
		    $str = '<tr><td colspan="8"><table width="100%" border="1" cellspacing="0" cellpadding="0" id="sku_list">
      <tr id="title">
        <td>产品ID</td>
		<td>产品图片</td>
        <td>产品名称</td>
        <td>规格</td>
        <td>单位</td>
        <td>数量</td>
        <td>条码数字</td>
        <td>原仓库</td>
        <td>目标仓库</td>
      </tr>';
		
		    if(empty($res)){
		        $str .="<tr><td colspan='8' align='center'>未选择任何商品</td></tr>";
		    }else{
		        foreach($res as $val){
		            $picArr = explode(',', $val['pic']);
		            $pic = "<a href=\"{$picArr[0]}\" target=\"_blank\"><img src=\"{$picArr[0]}/80\" /></a>";
		            $str .= '      <tr id="content">
	        <td>'.$val["pid"].'</td>
	        <td>'.$pic.'</td>
	        <td>'.$val["product"].'</td>
	        <td>'.$val["spec"].'</td>
	        <td>'.$val["unit"].'&nbsp;</td>
	        <td>'.($val["number"]+0).'</td>
	        <td>'.($val["barcode"]).'</td>
	        <td>'.$val["shop_from"].'</td>
	        <td>'.$val["shop_to"].'</td>
	      </tr>';
		        }
		    }
		
		    $str .= "</table></td></tr>";
		    die($str);
		}

		/**
		 * 商品列表、保存商品
		 */
		function settingProductList(){
		    global $db, $smarty, $segment, $config, $admin;
		    
		    $paperId = $_GET['paperId'];
		    $shopid_from = array();
		    if($paperId>0){
		        $sql = "select shopid_from,shopid_to,shop_from,shop_to from {$config->db_prefix}moving_paper where id={$paperId}";
		        $shopid_from = $db->GetRow($sql);
		    }
		    
		    if(!empty($_POST["action"]) && $_POST["action"]=="delete" && !empty($_POST['chk'])){//删除商品
	            $ids = "";
	            foreach ($_POST['chk'] as $id)
	            {
	                if(empty($ids)){
	                    $ids .= $id;
	                }else{
	                    $ids .= ",".$id;
	                }
	            }
	            $ids = trim($ids);
	            $sqlstr = "delete from {$config->db_prefix}moving where id in($ids)";
	            $result = $db->execute($sqlstr);
	            
	            header("location:".(empty($_GET['REFERER'])?"{$config->site_admin}m=inventory&s=moving.php&uri=settingProductList&paperId=".$paperId:$_GET['REFERER']));
		    }
		    
		    if(!empty($_POST["action"]) && $_POST["action"]=="saveProduct"){
		        //保存商品
		        if(!empty($_POST['chk'])){
	                $ids = "";
	                foreach ($_POST['chk'] as $id)
	                {
	                    if(empty($ids)){
	                        $ids .= $id;
	                    }else{
	                        $ids .= ",".$id;
	                    }
	                }
	                $ids = trim($ids);
	                $products = array();
	                $sql = "select b.id,b.pname,b.spec,c.unit,c.stocks from {$config->db_prefix}stocks c left join {$config->db_prefix}products a on a.product_sku_id=c.productid left join haiou_product_sku b on c.productid=b.id where c.productid in({$ids}) and c.shopid='{$shopid_from['shopid_from']}'";
	                $products = $db->GetAll($sql);
	                
	                $sql = "insert into {$config->db_prefix}moving (`paper_id`,`shopid_from`,`shop_from`,`shopid_to`,`shop_to`,`productid`,`product`,`spec`,`unit`,`number`) values";
	                $values = "";
	                foreach ($products as $val){
	                    //查看是否有已经添加
	                    $sqltemp = "select id from {$config->db_prefix}moving where paper_id={$paperId} and productid={$val['id']}";
	                    $exsistId = $db->GetOne($sqltemp);
	                    if($exsistId>0) continue;
	                    $val['pname'] = $db->qstr($val['pname']);
	                    $values .= empty($values)?"(":",(";
	                    $values .= "'{$paperId}',
	                    '{$shopid_from['shopid_from']}',
	                    '{$shopid_from['shop_from']}',
	                    '{$shopid_from['shopid_to']}',
	                    '{$shopid_from['shop_to']}',
	                    '{$val['id']}',
	                    {$val['pname']},
	                    '{$val['spec']}',
	                    '{$val['unit']}',
	                    '{$val['stocks']}')";
	                }
	                
	                $db->execute($sql.$values);
		        }
		        
    		    echo "<script>window.parent.main.location.reload();</script>";
    		    echo "<script>window.parent.DialogManager.close('moving');</script>";
    		    die;
		    }
		    
		    if(!empty($_POST["action"]) && $_POST["action"]=="saveNum"){
		        $id = $_POST['id'];
		        $num = $_POST['number'];
		        $sql = "update {$config->db_prefix}moving set number={$num} where id={$id}";
		        $db->execute($sql);
		        die('ok');
		    }
		    
		}
		
		/**
		 * 添加商品页面
		 */
		function showAddMoving(){
		    global $db, $smarty, $segment, $config, $admin;
		    
		    $paperId = $_GET['paperId'];
		    $shopid_from = array();
		    if($paperId>0){
		        $sql = "select shopid_from from {$config->db_prefix}moving_paper where id={$paperId}";
		        $shopid_from = $db->GetOne($sql);
		        
		        $_GET['shopid'] = $shopid_from;
		    }
		}
		
		/**
		 * 审核调拨单
		 */
		function audit()
		{
		    global $db, $segment, $config, $admin;
		    $paperId = intval($_GET['paperId']);
		    if(!($paperId>0))
		    {
		        exit('参数paperId错误');
		    }
		
		    $sql = "SELECT  `status` FROM `haiou_stock_moving_paper` WHERE id={$paperId}";
		    $paper = $db->GetRow($sql);
		    if(empty($paper))
		    {
		        exit('没有找到此调拨单');
		    }
		    if($paper['status']=='-1')
		    {
		        exit('此调拨单价已被删除');
		    }
		    if($paper['status']!='0')
		    {
		        exit('此调拨单状态不能置为已审核！');
		    }
		    
		    $sql = "SELECT id FROM `haiou_stock_moving` WHERE paper_id={$paperId}";
		    $res = $db->GetArray($sql);
		    
		    if(empty($res)){
		        exit('此调拨单未添加任何商品！');
		    }else{
    		    $sql = "SELECT id FROM `haiou_stock_moving` WHERE paper_id={$paperId} and number=0";
    		    $rest = $db->GetArray($sql);
    		    if(!empty($rest)){
    		        exit('调拨单中商品数量不能为0！');
    		    }
		    }
		    
		    $sqlstr = "UPDATE {$config->db_prefix}moving_paper SET `status`=1 WHERE `id`={$paperId}";
		    $result = $db->execute($sqlstr);
		    if($result)
		    {
		        header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=moving.php":$_SERVER['HTTP_REFERER']));
		    }
		    else
		    {
		        exit('系统错误，请重试');
		    }
		}
		
		/**
		 * 确认调拨单
		 */
		function confirm(){
		    global $db, $segment, $config, $admin;
		    $paperId = intval($_GET['paperId']);
		    if(!($paperId>0))
		    {
		        exit('参数paperId错误');
		    }
		    	
		    $sql = "SELECT  `status` FROM `haiou_stock_moving_paper` WHERE id={$paperId}";
		    $paper = $db->GetRow($sql);
		    if(empty($paper))
		    {
		        exit('没有找到此调拨单');
		    }
		    if($paper['status']=='-1')
		    {
		        exit('此调拨单已被删除');
		    }
		    if($paper['status']!='1')
		    {
		        exit('此调拨单状态不能置为确认状态！');
		    }
		
		    $sqlstr = "UPDATE {$config->db_prefix}moving_paper SET `status`=2 WHERE `id`={$paperId}";
		    $result = $db->execute($sqlstr);
		    
		    
		    if($result)
		    {
		        //确认后写入出库表
		        $sql = "select * from {$config->db_prefix}moving where paper_id={$paperId}";
		        $products = $db->GetArray($sql);
		        if(!empty($products)){
		            $values = "";
		            foreach ($products as $val)
		            {
		                if($val['number']>0){
		                    $val['product'] = $db->qstr($val['product']);
    		                $values .= empty($values)?"(":",(";
    		                $values .= "'{$paperId}',
		                    '{$val['shopid_from']}',
    		                '{$val['shop_from']}',
    		                '{$val['productid']}',
    		                {$val['product']},
    		                '{$val['spec']}',
    		                '{$val['unit']}',
    		                '{$val['number']}',
    		                '确认调拨单后自动写入',
    		                '5',
    		                '".strtotime(date('Y-m-d'))."')";
		                }
		            }
		            
		            $sqlstr = "insert into {$config->db_prefix}orders (lotnumber, shopid, shop, productid, product, spec, unit, number, memo,type, thedate) values ".$values;
		            $result = $db->execute($sqlstr);
		        }
		        header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=moving.php":$_SERVER['HTTP_REFERER']));
		    }
		    else
		    {
		        exit('系统错误，请重试');
		    }
		}
}
?>